package com.atguigu.yygh.order.controller;

import com.atguigu.yygh.common.R;
import com.atguigu.yygh.enums.PaymentTypeEnum;
import com.atguigu.yygh.order.service.PaymentService;
import com.atguigu.yygh.order.service.WeixinService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.util.Map;

/**
 * @author DongYu Zhou
 * @date 2022/7/8 23:14
 */
@Api(tags = "微信接口")
@RestController
@RequestMapping("/api/order/weixin")
public class WeixinController {
    @Autowired
    private WeixinService weixinService;
    @Autowired
    private PaymentService paymentService;

    /**
     * 下单 生成二维码
     */
    @ApiOperation(value = "生成二维码")
    @GetMapping("/createNative/{orderId}")
    public R createNative(
            @PathVariable("orderId") Long orderId) {
        Map<String,Object> map = weixinService.createNative(orderId);
        return R.ok().data(map);
    }

    @ApiOperation(value = "查询支付状态")
    @GetMapping("/queryPayStatus/{orderId}")
    public R queryPayStatus(@PathVariable("orderId") Long orderId){
       Map<String,String> resultMap= weixinService.queryPayStatus(orderId, PaymentTypeEnum.WEIXIN.getStatus());
//2判断支付失败
        if(resultMap==null){
            return R.error().message("微信扫码支付失败");
        }
        //3判断支付成功
        if("SUCCESS".equals(resultMap.get("trade_state"))){
            String outTradeNo = resultMap.get("out_trade_no");
            paymentService.paySuccess(outTradeNo,PaymentTypeEnum.WEIXIN.getStatus(),
                    resultMap);
            return R.ok().message("支付成功");
        }
        //4支付中
        return R.ok().message("支付中");

    }

}
